package com.cwj.blog.module.home

import android.annotation.SuppressLint
import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.inputmethod.InputMethodManager
import android.widget.LinearLayout
import androidx.recyclerview.widget.GridLayoutManager
import com.cwj.blog.R
import com.cwj.blog.base.BaseActivity
import com.cwj.blog.base.BaseRVAdapter
import com.cwj.blog.base.BaseRVHolder
import com.cwj.blog.bean.BlogBean
import com.cwj.blog.bean.GetDataType
import com.cwj.blog.databinding.ActivityMainBinding
import com.cwj.blog.module.add.AddBlogActivity
import com.cwj.blog.module.webview.WebViewActivity
import com.cwj.blog.util.LoadingDialog
import com.tencent.upgrade.core.DefaultUpgradeStrategyRequestCallback
import com.tencent.upgrade.core.UpgradeManager
import com.yechaoa.yutils.ToastUtil


class MainActivity : BaseActivity<ActivityMainBinding, HomePrensenter>(), HomeView,
    OnClickListener {

    private var skip = 1
    private val pageSize = 10
    private var title = ""
    private var adapter: BaseRVAdapter<BlogBean.DataBean>? = null
    private val addBlog = 201
    private var loadingDialog: LoadingDialog? = null

    override fun createPresenter(): HomePrensenter {
        return HomePrensenter(this)
    }

    override fun initView() {
        //应用升级
        UpgradeManager.getInstance()
            .checkUpgrade(false, null, DefaultUpgradeStrategyRequestCallback())

        loadingDialog = LoadingDialog(this@MainActivity, "")
        viewBinding.ivDelect.setOnClickListener(this)
        viewBinding.ivAdd.setOnClickListener(this)

        viewBinding.etInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                //检测到了输入的信息,展示删除按钮
                viewBinding.ivDelect.visibility = View.VISIBLE
            }

            override fun afterTextChanged(s: Editable) {
                //检测到了输入的信息,但是输入框是空的,隐藏删除按钮
                if (viewBinding.etInput.text.toString() == "") {
                    viewBinding.ivDelect.visibility = View.GONE
                }
            }
        })

        viewBinding.etInput.setOnKeyListener { _, keyCode, event -> //是否是回车键
            if (keyCode == KeyEvent.KEYCODE_ENTER && event!!.action == KeyEvent.ACTION_DOWN) {
                //隐藏键盘
                (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(
                    viewBinding.etInput.windowToken, InputMethodManager.HIDE_NOT_ALWAYS
                )

                title = viewBinding.etInput.text.toString()
                skip = 1
                presenter.page(skip, pageSize, title, GetDataType.REFRESH)
            }
            false
        }
    }

    @SuppressLint("InflateParams")
    override fun initData() {
        loadingDialog?.show()
        //博客查询
        presenter.page(skip, pageSize, title, GetDataType.GETDATA)

        adapter = object : BaseRVAdapter<BlogBean.DataBean>(R.layout.item_blog) {
            override fun onBindVH(holder: BaseRVHolder, data: BlogBean.DataBean, position: Int) {
                val ll: LinearLayout = holder.getView(R.id.ll)

                holder.setText(R.id.tvTitle, data.title)
                holder.setText(R.id.tvCreateTime, data.createTime)

                ll.setOnClickListener {
                    val intent = Intent(this@MainActivity, WebViewActivity::class.java)
                    intent.putExtra("url", data.url)
                    startActivity(intent)
                }
            }
        }

        //无数据视图显示
        val empty: View = LayoutInflater.from(this).inflate(R.layout.layout_no_data, null, false)
        (adapter as BaseRVAdapter<BlogBean.DataBean>).emptyView = empty

        //下拉刷新
        viewBinding.mRefreshLayout.setOnRefreshListener {
            skip = 1
            presenter.page(skip, pageSize, title, GetDataType.REFRESH)
        }

        //上拉加载更多
        viewBinding.mRefreshLayout.setOnLoadMoreListener {
            skip++
            presenter.page(skip, pageSize, title, GetDataType.LOADMORE)
        }

        viewBinding.mRecyclerView.adapter = adapter
        viewBinding.mRecyclerView.layoutManager = GridLayoutManager(this, 1) //列数设置
    }

    override fun pageData(blogBean: BlogBean?, type: Int?) {
        loadingDialog?.dismiss()

        val blogBeanList: List<BlogBean.DataBean>? = blogBean?.data
        when (type) {
            GetDataType.GETDATA -> adapter!!.setNewData(blogBeanList)
            GetDataType.REFRESH -> {
                adapter!!.setNewData(blogBeanList)
                viewBinding.mRefreshLayout.finishRefresh()
                viewBinding.mRefreshLayout.setNoMoreData(false)
            }

            GetDataType.LOADMORE -> if (!blogBeanList.isNullOrEmpty()) {
                adapter!!.addData(blogBeanList)
                if (blogBeanList.size < skip) {
                    viewBinding.mRefreshLayout.finishLoadMoreWithNoMoreData()
                } else {
                    viewBinding.mRefreshLayout.finishLoadMore()
                }
            } else {
                viewBinding.mRefreshLayout.finishLoadMoreWithNoMoreData()
            }
        }
    }

    override fun error(msg: String?) {
        loadingDialog?.dismiss()
        ToastUtil.showCenter(msg)
        viewBinding.mRefreshLayout.finishRefresh()
        viewBinding.mRefreshLayout.finishLoadMore()
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == addBlog && resultCode == RESULT_OK) {
            skip = 1
            presenter.page(skip, pageSize, title, GetDataType.REFRESH)
        }
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.ivDelect -> {
                viewBinding.etInput.setText("")
                title = ""
                skip = 1
                presenter.page(skip, pageSize, title, GetDataType.REFRESH)
            }

            R.id.ivAdd -> {
                val intent = Intent(this, AddBlogActivity::class.java)
                startActivityForResult(intent, addBlog)
            }

            else -> {}
        }
    }
}